package com.lingnan.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingnan.dto.CompanyCreateDTO;
import com.lingnan.dto.UpdateCompanyRequest;
import com.lingnan.dto.UpdateHrDTO;
import com.lingnan.entity.po.*;
import com.lingnan.entity.vo.Result;
import com.lingnan.feign.NotificationFeignClient;
import com.lingnan.mapper.*;
import com.lingnan.service.CompanyService;
import com.lingnan.utils.LoginContextHolder;
import com.lingnan.vo.CompanyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

// CompanyServiceImpl.java
@Service
@Transactional
@Slf4j
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {
    
    @Autowired
    private CompanyHrMapper companyHrMapper;
    
    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private JobApplicationMapper jobApplicationMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private InterviewMapper interviewMapper;

    @Autowired
    private JobPositionMapper jobPositionMapper;

    @Autowired
    private NotificationFeignClient notificationFeignClient;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Company createCompany(CompanyCreateDTO createDTO, Long userId) {
        // 检查该用户是否已经有企业信息
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getUserId, userId);
        Company existingCompany = this.getOne(queryWrapper);

        if (existingCompany != null) {
            throw new RuntimeException("该用户已经创建过企业信息");
        }

        // 创建企业信息
        Company company = new Company();
        BeanUtils.copyProperties(createDTO, company);
        company.setUserId(userId);
        company.setStatus(0); // 默认待审核状态
        company.setUpdateId(userId); // 设置更新者为当前用户

        // 保存到数据库
        this.save(company);
        //发送通知给管理员
        sendToAdmin2(userId, company);

        return company;
    }

    @Override
    public boolean deleteCompany(Long companyId) {
        // 1. 验证企业是否存在
        Company company = this.getById(companyId);
        if (company == null) {
            throw new RuntimeException("企业信息不存在");
        }

        // 2. 检查是否有正在进行的面试
        List<Interview> ongoingInterviews = interviewMapper.selectList(
                new LambdaQueryWrapper<Interview>()
                        .eq(Interview::getStatus, 0) // 待面试状态
                        .exists("SELECT 1 FROM company_hr hr WHERE hr.company_id = {0} AND hr.id = interview.hr_id", companyId)
        );
        if (!ongoingInterviews.isEmpty()) {
            throw new RuntimeException("该企业还有待进行的面试，无法删除");
        }

        // 3. 删除面试记录（已完成的面试）
        interviewMapper.delete(
                new LambdaQueryWrapper<Interview>()
                        .exists("SELECT 1 FROM company_hr hr WHERE hr.company_id = {0} AND hr.id = interview.hr_id", companyId)
        );

        // 4. 删除投递记录
        jobApplicationMapper.delete(
                new LambdaQueryWrapper<JobApplication>()
                        .exists("SELECT 1 FROM job_position jp WHERE jp.company_id = {0} AND jp.id = job_application.position_id", companyId)
        );

        // 5. 删除职位信息
        jobPositionMapper.delete(
                new LambdaQueryWrapper<JobPosition>()
                        .eq(JobPosition::getCompanyId, companyId)
        );

        // 6. 删除HR账号和HR信息
        List<CompanyHr> hrList = companyHrMapper.selectList(
                new LambdaQueryWrapper<CompanyHr>()
                        .eq(CompanyHr::getCompanyId, companyId)
        );

        for (CompanyHr hr : hrList) {
            // 删除HR的用户账号
            userAccountMapper.deleteById(hr.getUserAccountId());
        }

        // 批量删除HR信息
        if (!hrList.isEmpty()) {
            companyHrMapper.delete(
                    new LambdaQueryWrapper<CompanyHr>()
                            .eq(CompanyHr::getCompanyId, companyId)
            );
        }

        // 7. 删除企业信息
        int companyResult = this.baseMapper.deleteById(companyId);
        if (companyResult <= 0) {
            throw new RuntimeException("删除企业信息失败");
        }

        // 8. 删除企业主账号
        int userResult = userAccountMapper.deleteById(company.getUserId());
        if (userResult <= 0) {
            throw new RuntimeException("删除企业主账号失败");
        }

        log.info("成功删除企业，企业ID: {}, 企业名称: {}", companyId, company.getName());
        return true;
    }

    // CompanyServiceImpl.java 中修改 updateCompany 方法
    @Override
    public boolean updateCompany(UpdateCompanyRequest request) {
        try {
            // 1. 查询现有企业信息
            Company existingCompany = this.getById(request.getId());
            if (existingCompany == null) {
                throw new RuntimeException("企业信息不存在");
            }

            // 2. 只更新非空字段的企业信息
            Company updateCompany = new Company();
            updateCompany.setId(request.getId());
            updateCompany.setUpdateId(getCurrentUserId());

            if (!StringUtils.isEmpty(request.getName())) {
                updateCompany.setName(request.getName());
            }
            if (!StringUtils.isEmpty(request.getLicenseNo())) {
                updateCompany.setLicenseNo(request.getLicenseNo());
            }
            if (!StringUtils.isEmpty(request.getLicenseImg())) {
                updateCompany.setLicenseImg(request.getLicenseImg());
            }
            if (!StringUtils.isEmpty(request.getIndustry())) {
                updateCompany.setIndustry(request.getIndustry());
            }
            if (!StringUtils.isEmpty(request.getScale())) {
                updateCompany.setScale(request.getScale());
            }
            if (!StringUtils.isEmpty(request.getAddress())) {
                updateCompany.setAddress(request.getAddress());
            }
            if (!StringUtils.isEmpty(request.getWebsite())) {
                updateCompany.setWebsite(request.getWebsite());
            }

            // 3. 更新企业信息
            int companyResult = this.baseMapper.updateById(updateCompany);

            // 4. 更新关联的用户账号信息（如果有提供的话）
            boolean userResult = true;
            if (hasUserInfoToUpdate(request)) {
                UserAccount updateUser = new UserAccount();
                updateUser.setId(existingCompany.getUserId());

                if (!StringUtils.isEmpty(request.getNickName())) {
                    updateUser.setNickName(request.getNickName());
                }
                if (!StringUtils.isEmpty(request.getEmail())) {
                    updateUser.setEmail(request.getEmail());
                }
                if (!StringUtils.isEmpty(request.getPhone())) {
                    updateUser.setPhone(request.getPhone());
                }

                int userUpdateResult = userAccountMapper.updateById(updateUser);
                userResult = userUpdateResult > 0;
            }

            return companyResult > 0 && userResult;
        } catch (Exception e) {
            log.error("更新企业信息失败", e);
            throw new RuntimeException("更新企业信息失败: " + e.getMessage());
        }
    }

    // 检查是否有用户信息需要更新
    private boolean hasUserInfoToUpdate(UpdateCompanyRequest request) {
        return !StringUtils.isEmpty(request.getNickName()) ||
                !StringUtils.isEmpty(request.getEmail()) ||
                !StringUtils.isEmpty(request.getPhone());
    }

    @Override
    public CompanyVO getCompanyById(Long companyId) {
        Company company = this.getCompanyByUserId(companyId);
        if (company == null) {
            company = this.getById(companyId);

        }
        if (company == null) {
           return null;

        }
        // 查询关联的用户信息
        UserAccount userAccount = userAccountMapper.selectById(company.getUserId());

        // 转换为VO
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(company, companyVO);
        if (userAccount != null) {
            companyVO.setUsername(userAccount.getUsername());
            companyVO.setEmail(userAccount.getEmail());
            companyVO.setPhone(userAccount.getPhone());
            companyVO.setNickName(userAccount.getNickName());
            companyVO.setUserStatus(userAccount.getStatus());
        }

        return companyVO;
    }

    @Override
    public IPage<CompanyVO> getCompanyPage(Page<Company> page, String name, Integer status) {
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), Company::getName, name);
        wrapper.eq(status != null, Company::getStatus, status);
        wrapper.orderByDesc(Company::getCreatedAt);

        IPage<Company> companyPage = this.baseMapper.selectPage(page, wrapper);

        // 转换为VO并填充用户信息
        List<CompanyVO> companyVOList = companyPage.getRecords().stream().map(company -> {
            CompanyVO companyVO = new CompanyVO();
            BeanUtils.copyProperties(company, companyVO);

            // 查询关联的用户信息
            UserAccount userAccount = userAccountMapper.selectById(company.getUserId());
            if (userAccount != null) {
                companyVO.setUsername(userAccount.getUsername());
                companyVO.setEmail(userAccount.getEmail());
                companyVO.setPhone(userAccount.getPhone());
                companyVO.setNickName(userAccount.getNickName());
                companyVO.setUserStatus(userAccount.getStatus());
            }

            return companyVO;
        }).collect(Collectors.toList());

        IPage<CompanyVO> result = new Page<>();
        BeanUtils.copyProperties(companyPage, result);
        result.setRecords(companyVOList);

        return result;
    }


    @Override
    public boolean toggleCompanyStatus(Long companyId, Integer status) {
        try {
            Company company = new Company();
            company.setId(companyId);
            company.setStatus(status);
            company.setUpdateId(getCurrentUserId());

            int result = this.baseMapper.updateById(company);
            return result > 0;
        } catch (Exception e) {
            log.error("切换企业状态失败", e);
            throw new RuntimeException("切换企业状态失败: " + e.getMessage());
        }
    }

    @Override
    public Company getCompanyByUserId(Long userId) {
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Company::getUserId, userId);
        return this.baseMapper.selectOne(wrapper);
    }

    // 获取当前用户ID的方法（需要根据你的认证体系实现）
    private Long getCurrentUserId() {
        // 这里应该从Security Context或Session中获取当前用户ID
        Long loginId = Long.valueOf(LoginContextHolder.getLoginId());
        return loginId;
    }

    
    @Override
    public boolean addHr(CompanyHr companyHr, String hrPassword) {
        try {
            // 1. 先创建UserAccount记录
            UserAccount userAccount = new UserAccount();
            userAccount.setUsername(companyHr.getContactEmail()); // 使用邮箱作为用户名
            userAccount.setNickName(companyHr.getName());
            userAccount.setPassword(passwordEncoder.encode(hrPassword));
            userAccount.setEmail(companyHr.getContactEmail());
            userAccount.setPhone(companyHr.getContactPhone());
            userAccount.setUserType(3); // HR类型
            userAccount.setIsPrimary(false); // 非主账号
            userAccount.setStatus(1); // 启用状态
            
            int userResult = userAccountMapper.insert(userAccount);
            if (userResult <= 0) {
                throw new RuntimeException("创建HR用户账号失败");
            }
            
            // 2. 设置关联ID并插入CompanyHr记录
            companyHr.setUserAccountId(userAccount.getId());
            int hrResult = companyHrMapper.insert(companyHr);
            
            return hrResult > 0;
        } catch (Exception e) {
            log.error("添加HR失败", e);
            throw new RuntimeException("添加HR失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean deleteHr(Long hrId) {
        try {
            // 1. 查询HR记录获取用户账号ID
            CompanyHr companyHr = companyHrMapper.selectById(hrId);
            if (companyHr == null) {
                throw new RuntimeException("HR记录不存在");
            }

            //2.检查职位表
            Long count = jobPositionMapper.selectCount(new LambdaQueryWrapper<JobPosition>()
                    .eq(JobPosition::getHrId, companyHr.getCompanyId()));
            if(count>0){
                throw new RuntimeException("该HR已关联职位，请先解除关联关系");
            }
            // 3. 删除HR记录
            int hrResult = companyHrMapper.deleteById(hrId);
            if (hrResult <= 0) {
                throw new RuntimeException("删除HR记录失败");
            }
            
            // 4. 删除关联的用户账号
            int userResult = userAccountMapper.deleteById(companyHr.getUserAccountId());
            
            return userResult > 0;
        } catch (Exception e) {
            log.error("删除HR失败", e);
            throw new RuntimeException("删除HR失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateHr(UpdateHrDTO updateHrDTO) {
        try {
            // 1. 先查询原始HR记录
            CompanyHr existingHr = companyHrMapper.selectById(updateHrDTO.getId());
            if (existingHr == null) {
                throw new RuntimeException("HR记录不存在");
            }

            // 2. 构建HR表更新对象（只更新非空字段）
            CompanyHr hrToUpdate = new CompanyHr();
            hrToUpdate.setId(updateHrDTO.getId());

            boolean hrNeedUpdate = false;

            if (StringUtils.hasText(updateHrDTO.getName())) {
                hrToUpdate.setName(updateHrDTO.getName());
                hrNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getPosition())) {
                hrToUpdate.setPosition(updateHrDTO.getPosition());
                hrNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getContactEmail())) {
                hrToUpdate.setContactEmail(updateHrDTO.getContactEmail());
                hrNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getContactPhone())) {
                hrToUpdate.setContactPhone(updateHrDTO.getContactPhone());
                hrNeedUpdate = true;
            }

            // 3. 更新HR表
            int hrResult = 1; // 默认成功
            if (hrNeedUpdate) {
                hrResult = companyHrMapper.updateById(hrToUpdate);
            }
            // 同步更新面试记录中的hr姓名
            if (!Objects.equals(existingHr.getName(), updateHrDTO.getName())) {
                interviewMapper.updateHrNameBatch(existingHr.getName(), updateHrDTO.getName());
            }


            // 4. 构建UserAccount表更新对象（只更新非空字段）
            UserAccount userToUpdate = new UserAccount();
            userToUpdate.setId(existingHr.getUserAccountId());

            boolean userNeedUpdate = false;

            if (StringUtils.hasText(updateHrDTO.getName())) {
                userToUpdate.setNickName(updateHrDTO.getName());
                userNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getContactEmail())) {
                userToUpdate.setEmail(updateHrDTO.getContactEmail());
                userToUpdate.setUsername(updateHrDTO.getContactEmail()); // 同步更新用户名
                userNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getContactPhone())) {
                userToUpdate.setPhone(updateHrDTO.getContactPhone());
                userNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getPassword())) {
                userToUpdate.setPassword(passwordEncoder.encode(updateHrDTO.getPassword()));
                userNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getAvatar())) {
                userToUpdate.setAvatar(updateHrDTO.getAvatar());
                userNeedUpdate = true;
            }

            if (StringUtils.hasText(updateHrDTO.getContactPhone())) {
                userToUpdate.setPhone(updateHrDTO.getContactPhone());
                userNeedUpdate = true;
            }

            // 5. 更新UserAccount表
            int userResult = 1; // 默认成功
            if (userNeedUpdate) {
                userResult = userAccountMapper.updateById(userToUpdate);
            }

            return hrResult > 0 && userResult > 0;

        } catch (Exception e) {
            log.error("更新HR失败", e);
            throw new RuntimeException("更新HR失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<CompanyHr> getHrList(Long companyId) {
        LambdaQueryWrapper<CompanyHr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyHr::getCompanyId, companyId);
        wrapper.orderByDesc(CompanyHr::getCreatedAt);
        return companyHrMapper.selectList(wrapper);
    }
    
    @Override
    public CompanyHr getHrById(Long hrId) {
        return companyHrMapper.selectById(hrId);
    }
    
    @Override
    public boolean submitQualification(Long companyId) {
        try {
            Company company = this.getById(companyId);
            if (company == null) {
                throw new RuntimeException("企业信息不存在");
            }

            // 比如发送消息队列通知、邮件通知等
            sendToAdmin(companyId, company);
            return true;
        } catch (Exception e) {
            log.error("提交资质认证失败", e);
            throw new RuntimeException("提交资质认证失败: " + e.getMessage());
        }
    }

    private void sendToAdmin(Long companyId, Company company) {
        Long companyUserId = getCurrentUserId();
        Long adminId = 1L;//ZSH TODO 2025/8/1 管理员id未确定暂时用1
        String title = "您有新的企业资质认证，请注意查看";
        String content = "【企业】："+ company.getName()+"【companyId】:"+ companyId +"   上传资质认证！";
        notificationFeignClient.sendPersonalNotification(companyUserId, adminId, title, content, 1);
    }
    private void sendToAdmin2(Long userId, Company company) {
        Long adminId = 1L;//ZSH TODO 2025/8/1 管理员id未确定暂时用1
        String title = "您有新的企业资质认证，请注意查看";
        String content = "【企业】："+ company.getName()+"  【companyId】:"+ company.getId() +" 上传资质认证！";
        notificationFeignClient.sendPersonalNotification(userId, adminId, title, content, 1);
    }

}